package com.coffee.sku.service.sku.impl;


import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.platform.query.PlatformBaseDeployQuery;
import com.coffee.admin.service.platform.bean.PlatformBaseDeploy;
import com.coffee.admin.service.platform.dao.PlatformBaseDeployDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.PlatformBaseDeployTypeEnum;
import com.coffee.core.enums.SkuCategoryAttributeTypeEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.DTOUtils;
import com.coffee.core.util.StringUtil;
import com.coffee.job.service.quartz.job.SkuCancelWatiPartOrderJob;
import com.coffee.sku.api.sku.query.SkuCategoryAttributeQuery;
import com.coffee.sku.api.sku.req.AddSkuCategoryAttributeReq;
import com.coffee.sku.api.sku.req.AddSkuCategoryAttributeSubReq;
import com.coffee.sku.api.sku.result.SkuCategoryAttributeDetailResult;
import com.coffee.sku.api.sku.result.SkuCategoryAttributeResult;
import com.coffee.sku.api.sku.result.SkuCategoryAttributeSubResult;
import com.coffee.sku.api.sku.service.SkuCategoryAttributeService;
import com.coffee.sku.service.sku.bean.SkuCategory;
import com.coffee.sku.service.sku.bean.SkuCategoryAttribute;
import com.coffee.sku.service.sku.dao.SkuCategoryAttributeDao;
import com.coffee.sku.service.sku.dao.SkuCategoryDao;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@DubboService(dynamic = true)
public class SkuCategoryAttributeServiceImpl implements SkuCategoryAttributeService {
    private static final Logger logger = LoggerFactory.getLogger(SkuCategoryAttributeServiceImpl.class);

    @Resource
    private SkuCategoryAttributeDao skuCategoryAttributeDao;
    @Resource
    private SkuCategoryDao skuCategoryDao;
    @Resource
    private PlatformBaseDeployDao platformBaseDeployDao;

    @Override
    public Page<SkuCategoryAttributeDetailResult> getPager(SkuCategoryAttributeQuery param, PagerInfo pr) {
        Page<SkuCategoryAttributeDetailResult> pager = new Page<SkuCategoryAttributeDetailResult>(pr.getStart(), pr.getPageSize());
        Integer count = skuCategoryAttributeDao.countGroupByCategoryId(param);
        pager.setTotalPage(count);
        List<SkuCategoryAttributeDetailResult> skuCategoryAttributeDetailResults = new ArrayList<>();
        if (count > 0) {
            List<Integer> list = skuCategoryAttributeDao.pageGroupByCategoryId(param, pr.getStart(), pr.getPageSize());
            for (Integer integer : list) {
                SkuCategoryAttributeDetailResult skuCategoryAttributeDetailResult = new SkuCategoryAttributeDetailResult();
                SkuCategory skuCategory = skuCategoryDao.findById(integer);
                skuCategoryAttributeDetailResult.setCategoryId(integer);
                skuCategoryAttributeDetailResult.setCategoryName(skuCategory.getName());
                SkuCategoryAttributeQuery skuCategoryAttributeQuery = new SkuCategoryAttributeQuery();
                skuCategoryAttributeQuery.setCategoryId(integer);
                skuCategoryAttributeQuery.setType(SkuCategoryAttributeTypeEnum.SKU.getCode());
                List<SkuCategoryAttribute> skuList = skuCategoryAttributeDao.list(skuCategoryAttributeQuery);
                if (skuList.size() > 0) {
                    List<SkuCategoryAttributeSubResult> categoryAttributeSubResults = DTOUtils.convertList(skuList, SkuCategoryAttributeSubResult.class);
                    skuCategoryAttributeDetailResult.setSkuAttributeResults(categoryAttributeSubResults);
                }
                SkuCategoryAttributeQuery categoryParam = new SkuCategoryAttributeQuery();
                categoryParam.setCategoryId(integer);
                categoryParam.setType(SkuCategoryAttributeTypeEnum.CATEGORY.getCode());
                List<SkuCategoryAttribute> categoryList = skuCategoryAttributeDao.list(categoryParam);
                if (categoryList.size() > 0) {
                    List<SkuCategoryAttributeSubResult> categoryAttributeSubResults = DTOUtils.convertList(categoryList, SkuCategoryAttributeSubResult.class);
                    skuCategoryAttributeDetailResult.setCategoryAttributeResults(categoryAttributeSubResults);
                }
                skuCategoryAttributeDetailResults.add(skuCategoryAttributeDetailResult);
            }
            pager.setData(skuCategoryAttributeDetailResults);
        }
        return pager;
    }

    @Override
    public Integer count(SkuCategoryAttributeQuery param) {
        Integer count = skuCategoryAttributeDao.count(param);
        return count;
    }

    @Override
    public SkuCategoryAttributeDetailResult getDetailByCategoryId(Integer categoryId) {
        SkuCategoryAttributeDetailResult skuCategoryAttributeDetailResult = new SkuCategoryAttributeDetailResult();
        SkuCategory skuCategory = skuCategoryDao.findById(categoryId);
        if (skuCategory == null) {
            return skuCategoryAttributeDetailResult;
        }
        skuCategoryAttributeDetailResult.setCategoryId(categoryId);
        skuCategoryAttributeDetailResult.setCategoryName(skuCategory.getName());
        List<SkuCategoryAttributeSubResult> skuAttributeResults = new ArrayList<>();
        SkuCategoryAttributeQuery param = new SkuCategoryAttributeQuery();
        param.setCategoryId(categoryId);
        param.setType(SkuCategoryAttributeTypeEnum.SKU.getCode());
        List<SkuCategoryAttribute> skuList = skuCategoryAttributeDao.list(param);
        if (skuList.size() > 0) {
            for (SkuCategoryAttribute skuCategoryAttribute : skuList) {
                SkuCategoryAttributeSubResult skuCategoryAttributeSubResult = new SkuCategoryAttributeSubResult();
                skuCategoryAttributeSubResult.setPlatformBaseDeployId(skuCategoryAttribute.getPlatformBaseDeployId());
                skuCategoryAttributeSubResult.setPlatformBaseDeployName(skuCategoryAttribute.getPlatformBaseDeployName());
                skuCategoryAttributeSubResult.setPlatformBaseDeployType(skuCategoryAttribute.getPlatformBaseDeployType());
                skuCategoryAttributeSubResult.setCompany(skuCategoryAttribute.getCompany());
                if (skuCategoryAttribute.getPlatformBaseDeployType().equals(PlatformBaseDeployTypeEnum.LISTBOX.getCode())) {
                    PlatformBaseDeployQuery platformBaseDeployQuery = new PlatformBaseDeployQuery();
                    platformBaseDeployQuery.setPid(skuCategoryAttribute.getPlatformBaseDeployId());
                    List<PlatformBaseDeploy> platformBaseDeploys = platformBaseDeployDao.list(platformBaseDeployQuery);
                    if (platformBaseDeploys.size() > 0) {
                        List<String> collect = platformBaseDeploys.stream().map(PlatformBaseDeploy::getName).collect(Collectors.toList());
                        skuCategoryAttributeSubResult.setPlatformBaseDeploySecondNames(collect);
                    }
                }
                skuAttributeResults.add(skuCategoryAttributeSubResult);
            }
            skuCategoryAttributeDetailResult.setSkuAttributeResults(skuAttributeResults);
        }
        List<SkuCategoryAttributeSubResult> categoryAttributeSubResults = new ArrayList<>();
        SkuCategoryAttributeQuery categoryParam = new SkuCategoryAttributeQuery();
        categoryParam.setCategoryId(categoryId);
        categoryParam.setType(SkuCategoryAttributeTypeEnum.CATEGORY.getCode());
        List<SkuCategoryAttribute> categoryList = skuCategoryAttributeDao.list(categoryParam);
        if (categoryList.size() > 0) {
            for (SkuCategoryAttribute skuCategoryAttribute : categoryList) {
                SkuCategoryAttributeSubResult categoryAttributeSubResult = new SkuCategoryAttributeSubResult();
                categoryAttributeSubResult.setPlatformBaseDeployId(skuCategoryAttribute.getPlatformBaseDeployId());
                categoryAttributeSubResult.setPlatformBaseDeployName(skuCategoryAttribute.getPlatformBaseDeployName());
                categoryAttributeSubResult.setPlatformBaseDeployType(skuCategoryAttribute.getPlatformBaseDeployType());
                categoryAttributeSubResult.setCompany(skuCategoryAttribute.getCompany());
                if (skuCategoryAttribute.getPlatformBaseDeployType().equals(PlatformBaseDeployTypeEnum.LISTBOX.getCode())) {
                    PlatformBaseDeployQuery platformBaseDeployQuery = new PlatformBaseDeployQuery();
                    platformBaseDeployQuery.setPid(skuCategoryAttribute.getPlatformBaseDeployId());
                    List<PlatformBaseDeploy> platformBaseDeploys = platformBaseDeployDao.list(platformBaseDeployQuery);
                    if (platformBaseDeploys.size() > 0) {
                        List<String> collect = platformBaseDeploys.stream().map(PlatformBaseDeploy::getName).collect(Collectors.toList());
                        categoryAttributeSubResult.setPlatformBaseDeploySecondNames(collect);
                    }
                }
                categoryAttributeSubResults.add(categoryAttributeSubResult);
            }
            skuCategoryAttributeDetailResult.setCategoryAttributeResults(categoryAttributeSubResults);
        }
        return skuCategoryAttributeDetailResult;
    }

    @Override
    public List<SkuCategoryAttributeResult> getList(SkuCategoryAttributeQuery param, PagerInfo pr) {
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SkuCategoryAttributeResult.class);
    }

    @Override
    public List<SkuCategoryAttributeResult> getList(SkuCategoryAttributeQuery param) {
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.page(param, 0, Integer.MAX_VALUE);
        List<SkuCategoryAttributeResult> skuCategoryAttributeResults = DTOUtils.convertList(list, SkuCategoryAttributeResult.class);
        for (SkuCategoryAttributeResult skuCategoryAttributeResult : skuCategoryAttributeResults) {
            if (skuCategoryAttributeResult.getPlatformBaseDeployType().equals(PlatformBaseDeployTypeEnum.LISTBOX.getCode())) {
                PlatformBaseDeployQuery platformBaseDeployQuery = new PlatformBaseDeployQuery();
                platformBaseDeployQuery.setPid(skuCategoryAttributeResult.getPlatformBaseDeployId());
                List<PlatformBaseDeploy> platformBaseDeploys = platformBaseDeployDao.list(platformBaseDeployQuery);
                if (platformBaseDeploys.size() > 0) {
                    List<String> collect = platformBaseDeploys.stream().map(PlatformBaseDeploy::getName).collect(Collectors.toList());
                    skuCategoryAttributeResult.setPlatformBaseDeploySecondList(collect);
                }
            }
        }
        return skuCategoryAttributeResults;
    }

    @Override
    public List<SkuCategoryAttributeResult> getList() {
        SkuCategoryAttributeQuery param = new SkuCategoryAttributeQuery();
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SkuCategoryAttributeResult.class);
    }


    @Override
    public void deleteByCategory(Integer id) {
        skuCategoryAttributeDao.deleteById(id);
    }

    @Override
    public void add(AddSkuCategoryAttributeReq result) throws BusinessException {
        ValidateBusinessException.assertNonNull(result.getCategoryId(), ExceptionEnum.ERROR_1317);
        ValidateBusinessException.assertNonNull(result.getSkuCategoryAttributeSubReqList(), ExceptionEnum.ERROR_1350);
        SkuCategoryAttributeQuery param = new SkuCategoryAttributeQuery();
        param.setCategoryId(result.getCategoryId());
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.list(param);
        if (list != null && list.size() > 0) {
            throw BusinessException.build(ExceptionEnum.ERROR_1349);
        }
        for (AddSkuCategoryAttributeSubReq addSkuCategoryAttributeSubReq : result.getSkuCategoryAttributeSubReqList()) {
            SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
            skuCategoryAttribute.setCategoryId(result.getCategoryId());
            skuCategoryAttribute.setPlatformBaseDeployId(addSkuCategoryAttributeSubReq.getPlatformBaseDeployId());
            skuCategoryAttribute.setType(SkuCategoryAttributeTypeEnum.SKU.getCode());
            skuCategoryAttribute.setCompany(addSkuCategoryAttributeSubReq.getCompany());
            skuCategoryAttribute.setCreateTime(new Date());
            skuCategoryAttributeDao.insert(skuCategoryAttribute);
        }
        if (result.getCategoryAttributeSubReqList() != null && result.getCategoryAttributeSubReqList().size() > 0) {
            for (AddSkuCategoryAttributeSubReq addCategoryAttributeSubReq : result.getCategoryAttributeSubReqList()) {
                SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
                skuCategoryAttribute.setCategoryId(result.getCategoryId());
                skuCategoryAttribute.setPlatformBaseDeployId(addCategoryAttributeSubReq.getPlatformBaseDeployId());
                skuCategoryAttribute.setType(SkuCategoryAttributeTypeEnum.CATEGORY.getCode());
                skuCategoryAttribute.setCompany(addCategoryAttributeSubReq.getCompany());
                skuCategoryAttribute.setCreateTime(new Date());
                skuCategoryAttributeDao.insert(skuCategoryAttribute);
            }
        }
    }

    @Override
    public void update(AddSkuCategoryAttributeReq result) throws BusinessException {
        ValidateBusinessException.assertNonNull(result.getCategoryId(), ExceptionEnum.ERROR_1317);
        List<AddSkuCategoryAttributeSubReq> skuCategoryAttributeSubReqList = result.getSkuCategoryAttributeSubReqList();
        ValidateBusinessException.assertNonNull(skuCategoryAttributeSubReqList, ExceptionEnum.ERROR_1350);
        SkuCategoryAttributeQuery param = new SkuCategoryAttributeQuery();
        param.setCategoryId(result.getCategoryId());
        param.setType(SkuCategoryAttributeTypeEnum.SKU.getCode());
        List<SkuCategoryAttribute> skuList = skuCategoryAttributeDao.list(param);
        List<Integer> existencePlatformBaseDeployIds = skuList.stream().map(rl -> rl.getPlatformBaseDeployId()).collect(Collectors.toList());
        List<Integer> platformBaseDeployIds = skuCategoryAttributeSubReqList.stream().map(rl -> rl.getPlatformBaseDeployId()).collect(Collectors.toList());
        Map<Integer, AddSkuCategoryAttributeSubReq> map = skuCategoryAttributeSubReqList.stream().collect(Collectors.toMap(AddSkuCategoryAttributeSubReq::getPlatformBaseDeployId, i -> i));
        //删除
        Collection subtract = CollectionUtils.subtract(existencePlatformBaseDeployIds, platformBaseDeployIds);
        List<Integer> deleteList = new ArrayList<>(subtract);
        if (deleteList.size() > 0) {
            skuCategoryAttributeDao.deleteByCategoryId(deleteList, result.getCategoryId());
        }
        //添加
        Collection addSubtract = CollectionUtils.subtract(platformBaseDeployIds, existencePlatformBaseDeployIds);
        List<Integer> addList = new ArrayList<>(addSubtract);
        List<SkuCategoryAttribute> addDailiMerchantSkuIdList = new ArrayList<>();
        if (addList.size() > 0) {
            for (Integer skuId : addList) {
                SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
                skuCategoryAttribute.setCategoryId(result.getCategoryId());
                skuCategoryAttribute.setPlatformBaseDeployId(skuId);
                skuCategoryAttribute.setType(SkuCategoryAttributeTypeEnum.SKU.getCode());
                AddSkuCategoryAttributeSubReq addSkuCategoryAttributeSubReq = map.get(skuId);
                skuCategoryAttribute.setCompany(addSkuCategoryAttributeSubReq.getCompany());
                skuCategoryAttribute.setCreateTime(new Date());
                addDailiMerchantSkuIdList.add(skuCategoryAttribute);
            }
            skuCategoryAttributeDao.insertBatch(addDailiMerchantSkuIdList);
        }
        //修改
        Collection updateSubtract = CollectionUtils.intersection(platformBaseDeployIds, existencePlatformBaseDeployIds);
        List<Integer> updateList = new ArrayList<>(updateSubtract);
        if (updateList.size() > 0) {
            for (Integer skuId : updateList) {
                SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
                AddSkuCategoryAttributeSubReq addSkuCategoryAttributeSubReq = map.get(skuId);
                if (StringUtils.isNotEmpty(addSkuCategoryAttributeSubReq.getCompany())) {
                    skuCategoryAttribute.setCategoryId(result.getCategoryId());
                    skuCategoryAttribute.setPlatformBaseDeployId(skuId);
                    skuCategoryAttribute.setCompany(addSkuCategoryAttributeSubReq.getCompany());
                    skuCategoryAttributeDao.updateByCategoryId(skuCategoryAttribute);
                }
            }
        }
        SkuCategoryAttributeQuery categoryAttributeQuery = new SkuCategoryAttributeQuery();
        categoryAttributeQuery.setCategoryId(result.getCategoryId());
        categoryAttributeQuery.setType(SkuCategoryAttributeTypeEnum.CATEGORY.getCode());
        List<SkuCategoryAttribute> categoryList = skuCategoryAttributeDao.list(categoryAttributeQuery);
        List<Integer> categoryIds = categoryList.stream().map(rl -> rl.getPlatformBaseDeployId()).collect(Collectors.toList());
        if (result.getCategoryAttributeSubReqList() != null && result.getCategoryAttributeSubReqList().size() > 0) {
            List<Integer> categoryPlatformBaseDeployIds = result.getCategoryAttributeSubReqList().stream().map(rl -> rl.getPlatformBaseDeployId()).collect(Collectors.toList());
            Map<Integer, AddSkuCategoryAttributeSubReq> categoryMap = result.getCategoryAttributeSubReqList().stream().collect(Collectors.toMap(AddSkuCategoryAttributeSubReq::getPlatformBaseDeployId, i -> i));
            //删除
            Collection categorySubtract = CollectionUtils.subtract(categoryIds, categoryPlatformBaseDeployIds);
            List<Integer> categoryDeleteList = new ArrayList<>(categorySubtract);
            if (categoryDeleteList.size() > 0) {
                skuCategoryAttributeDao.deleteByCategoryId(categoryDeleteList, result.getCategoryId());
            }
            //添加
            Collection addCategorySubtract = CollectionUtils.subtract(categoryPlatformBaseDeployIds, categoryIds);
            List<Integer> addCategoryList = new ArrayList<>(addCategorySubtract);
            List<SkuCategoryAttribute> addCategoryDailiMerchantSkuIdList = new ArrayList<>();
            if (addCategoryList.size() > 0) {
                for (Integer skuId : addCategoryList) {
                    SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
                    skuCategoryAttribute.setCategoryId(result.getCategoryId());
                    skuCategoryAttribute.setPlatformBaseDeployId(skuId);
                    skuCategoryAttribute.setType(SkuCategoryAttributeTypeEnum.CATEGORY.getCode());
                    AddSkuCategoryAttributeSubReq addSkuCategoryAttributeSubReq = map.get(skuId);
                    if (addSkuCategoryAttributeSubReq != null)
                        skuCategoryAttribute.setCompany(addSkuCategoryAttributeSubReq.getCompany());
                    skuCategoryAttribute.setCreateTime(new Date());
                    addCategoryDailiMerchantSkuIdList.add(skuCategoryAttribute);
                }
                skuCategoryAttributeDao.insertBatch(addCategoryDailiMerchantSkuIdList);
            }
            //修改
            Collection updateCategorySubtract = CollectionUtils.intersection(categoryPlatformBaseDeployIds, categoryIds);
            List<Integer> updateCategoryList = new ArrayList<>(updateCategorySubtract);
            if (updateCategoryList.size() > 0) {
                for (Integer skuId : updateCategoryList) {
                    SkuCategoryAttribute skuCategoryAttribute = new SkuCategoryAttribute();
                    AddSkuCategoryAttributeSubReq addSkuCategoryAttributeSubReq = categoryMap.get(skuId);
                    if (StringUtils.isNotEmpty(addSkuCategoryAttributeSubReq.getCompany())) {
                        skuCategoryAttribute.setCategoryId(result.getCategoryId());
                        skuCategoryAttribute.setPlatformBaseDeployId(skuId);
                        skuCategoryAttribute.setCompany(addSkuCategoryAttributeSubReq.getCompany());
                        skuCategoryAttributeDao.updateByCategoryId(skuCategoryAttribute);
                    }
                }
            }
        } else if (categoryIds.size() > 0) {
            skuCategoryAttributeDao.deleteByCategoryId(categoryIds, result.getCategoryId());
        }
    }

    @Override
    public Map<Integer, SkuCategoryAttributeResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SkuCategoryAttributeResult> map = new HashMap<Integer, SkuCategoryAttributeResult>();
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.findByIds(StringUtil.setToList(idSet));
        List<SkuCategoryAttributeResult> resultList = DTOUtils.convertList(list, SkuCategoryAttributeResult.class);
        for (SkuCategoryAttributeResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, SkuCategoryAttributeResult> getItemMap() {
        Map<Integer, SkuCategoryAttributeResult> map = new HashMap<Integer, SkuCategoryAttributeResult>();
        SkuCategoryAttributeQuery param = new SkuCategoryAttributeQuery();
        List<SkuCategoryAttribute> list = skuCategoryAttributeDao.page(param, 0, Integer.MAX_VALUE);
        List<SkuCategoryAttributeResult> resultList = DTOUtils.convertList(list, SkuCategoryAttributeResult.class);
        for (SkuCategoryAttributeResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }


}
